﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.Reflection;
using TinyERP.Framework.Plugin;
using System.Globalization;
using System.Threading;
namespace TinyERP.Framework
{
    public class ModuleResourceManager
    {
        private IDictionary<string, ResourceManager> moduleResourceStorage;
        private static ModuleResourceManager instance;
        private CultureInfo oldCultureInfo;
        private ModuleResourceManager()
        {
            moduleResourceStorage = new Dictionary<string, ResourceManager>();
        }
        public static ModuleResourceManager GetInstance()
        {
            if (instance == null)
            {
                instance = new ModuleResourceManager();
            }
            return instance;
        }

        public string GetString(string key, string moduleName)
        {
            string result = "";
            try
            {
                ResourceManager resourceManager = GetResourceManagerOfModule(moduleName);
                result = resourceManager.GetString(key);
            }
            catch
            {
                return key;
            }
            return result;
        }

        private ResourceManager GetResourceManagerOfModule(string moduleName)
        {
            CultureInfo newCultureInfo = Thread.CurrentThread.CurrentUICulture;
            if (oldCultureInfo == null || oldCultureInfo.DisplayName != newCultureInfo.DisplayName)
            {
                UpdateAllResourceWithCurrentLanguage();
                oldCultureInfo = newCultureInfo;
            }

            string resourceKey = moduleName + ".Resource.ModuleResource";
            ResourceManager resourceManager = null;
            if (!moduleResourceStorage.ContainsKey(resourceKey))
            {
                Assembly assembly = PluginManager.GetInstance().GetAssemblyOfModule(moduleName);
                resourceManager = new ResourceManager(resourceKey, assembly);
                moduleResourceStorage[resourceKey] = resourceManager;
            }
            else
            {
                resourceManager = moduleResourceStorage[resourceKey];
            }
            return resourceManager;
        }
        private void UpdateAllResourceWithCurrentLanguage()
        {
            foreach (string resourceKey in moduleResourceStorage.Keys)
            {
                string assemblyName = resourceKey.Replace(".Resource.ModuleResource", "");
                Assembly assembly = PluginManager.GetInstance().GetAssemblyOfModule(assemblyName);
                moduleResourceStorage[resourceKey] = new ResourceManager(resourceKey, assembly);
            } 
        }
    }
}
